package grit

import (
	"gitee.com/segeln/grit/toolkit"
	//pb "github.com/segeln/grit/example/protoc"
	"gitee.com/segeln/grit/conf"
	//"gitee.com/segeln/grit/registry"
	//consule "gitee.com/segeln/grit/registry/consule"
	"gitee.com/segeln/grit/gatehttp"
	"gitee.com/segeln/grit/log"
	"gitee.com/segeln/grit/registry"
	consule "gitee.com/segeln/grit/registry/consule"
	"google.golang.org/grpc"
)

//type Option func(*Options)

//func RegisterHelloServer(s *grpc.Server, srv HelloServer)

//type RegisterServer2 func(*grpc.Server, interface{})

//type RegisterServer func(*grpc.Server, pb.HelloServer)

//s *grpc.Server, srv HelloServer

//type RegisterServer func(interface{})

var (
	//当前系统的注册管理器
	CurrentRegistry registry.Registry
)

type Service interface {
	// The service name
	//Name() string
	// Init initialises options
	Init(...conf.SetConfigItem)

	Server() *grpc.Server

	Register() registry.Registry
	// Options returns the current options
	//Options() Options
	// Client is used to call services
	//	Client() client.Client
	// Server is for handling requests and events
	//	Server() server.Server
	// Run the service
	Run() error
	//RegisterService(*grpc.ServiceDesc, interface{})

	//RegisterService2(RegisterServer2, interface{})
	//RegisterService(RegisterServer, pb.HelloServer)

	// The service implementation
	//	String() string
}

/*

type Options struct {
	Port      int
	Name      string
	ServiceID string
	Version   string
	Registry  registry.Registry
}

func Port(port int) Option {
	return func(o *Options) {
		o.Port = port
	}
}
func Name(name string) Option {
	return func(o *Options) {
		o.Name = name
	}
}

func ServiceID(sid string) Option {
	return func(o *Options) {
		o.ServiceID = sid
	}
}

func newOptions(opts ...Option) Options {
	//var wdPath, confPath, Logdir, BIdir *string
	//var ProcessID *string
	opt := Options{
		Port:     9003,
		Registry: consule.NewConsulRegistry(), //.DefaultRegistry,
	}
	for _, o := range opts {
		o(&opt)
	}
	return opt
}
*/
func NewService(opts ...conf.SetConfigItem) Service {

	conf.Conf = conf.ParseConfig()
	log.Infoln("cfg:", *conf.Conf)
	s := new(service)

	conf.NewConfigs(conf.Conf, opts...)

	s.opts = conf.Conf // options

	s.Registry = consule.NewConsulRegistry(s.opts.RegistryCfg.Address, toolkit.Service_Style_GRPC)
	CurrentRegistry = s.Registry
	log.Infoln("s.opts.port:", s.opts.Port)
	//实现gRPC Server

	optsgrpc := make([]grpc.ServerOption, 0)
	optsgrpc = append(optsgrpc, grpc.UnaryInterceptor(s.Interceptor))

	s.Ser = grpc.NewServer(optsgrpc...)
	return s
}
func NewGateHttp(opts ...conf.SetConfigItem) *gatehttp.GateHttp {
	conf.Conf = conf.ParseConfig()
	log.Infoln("cfg:", *conf.Conf)

	conf.NewConfigs(conf.Conf, opts...)

	gh := &gatehttp.GateHttp{}
	gh.SetOpts(conf.Conf)
	gh.Registry = consule.NewConsulRegistry(gh.GetOpts().RegistryCfg.Address, toolkit.Service_Style_Http)
	CurrentRegistry = gh.Registry
	return gh
}
